package com.digitalchina.lxnsy.activity.old;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessTechnologies;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.ConsultDynamicDetailVO;
import com.digitalchina.lxnsy.entity.TechnologiesCommentVO;
import com.digitalchina.lxnsy.interfaces.JavaScriptinterface;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.TechnologiesCommentHolder;
import com.digitalchina.lxnsy.xml.UserXML;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/2/9 10:18
 * 修改备注：
 * ================================================
 */
public class MessageContentActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.et_msg)
    EditText etMsg;
    @Bind(R.id.tv_send)
    TextView tvSend;
    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
    private List<TechnologiesCommentVO> voList = new ArrayList<>();
    private View headView;//头布局
    private WebView webView;
    private ConsultDynamicDetailVO vo;
    private String url = "";
    private String detailId = "";
    boolean isClear = false;
    boolean onProgressChanged = true;


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_message_content);
        setTitle("信息内容");
    }

    @Override
    public void initMember() {

//        vo = (ConsultDynamicDetailVO) getIntent().getSerializableExtra("ConsultDynamicDetailVO");
//        detailId = vo.getDetailId();
        detailId = (String) getIntent().getSerializableExtra("id");
        url = URL.URL_CONSULT_DETAIL_H5 + detailId;

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapter(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new TechnologiesCommentHolder(parent);
            }
        });


        headView = LayoutInflater.from(this).inflate(R.layout.view_headview_webview, null);
        webView = headView.findViewById(R.id.web_view);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        webView.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        webView.addJavascriptInterface(new JavaScriptinterface(this),
                "android");

        webView.loadUrl(url);

        webView.setWebChromeClient(new WebChromeClient() {
                                       public void onProgressChanged(WebView view, int progress) {
                                           if (progress == 100 && onProgressChanged) {
                                               onProgressChanged = false;
                                               onRefresh();
                                           }
                                       }
                                   }
        );


        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {

                return headView;
            }

            @Override
            public void onBindView(View headerView) {


            }
        });

    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!"1".equals(UserXML.getLoginStatus(MessageContentActivity.this))) {
                    GotoUtil.gotoActivity(MessageContentActivity.this, LoginGuideActivity.class);
                    return;
                }

                if (StringUtil.isEditEmpty(etMsg)) {
                    showToast("请输入评论内容");
                    return;
                }

                BusinessTechnologies.publishComment(MessageContentActivity.this, detailId, etMsg.getText().toString(), "1", mHandler);
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (recyclerView == null)
                    return;

                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);
                switch (msg.what) {
                    case MSG.MSG_GET_COMMENT_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_COMMENT_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_PUBLISH_COMMENT_SUCCESS:
                        showToast("评论成功");
                        // 隐藏软键盘
                        InputMethodManager imm = (InputMethodManager) etMsg
                                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm.isActive()) {
                            imm.hideSoftInputFromWindow(etMsg.getApplicationWindowToken(), 0);
                        }
                        etMsg.setText("");
                        onRefresh();
                        break;
                    case MSG.MSG_PUBLISH_COMMENT_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBean(object.toString(), "body", "list", TechnologiesCommentVO.class);

        if (page == 1 && isClear) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);

        if (voList != null) {
            if (voList.size() < limit) {
                adapter.stopMore();
            }
        }

        isClear = true;
    }

    @Override
    public void rightOnClick() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessTechnologies.getCommentList(this, detailId, "1", page, limit, mHandler);
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            BusinessTechnologies.getCommentList(this, detailId, "1", page, limit, mHandler);
        }
    }


}
